"use client";
import useBasket from "@/app/hooks/basket.hook";
import { useNotifications } from "@/app/hooks/notification.hook";
import CardItem from "@/components/cart-item";
import { GATEWAY_URL } from "@/lib/env";
import Item from "@/shared/item";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

export default function CartPage() {
  const router = useRouter();
  const { showError } = useNotifications();
  const { selected, findQuantity } = useBasket();
  const [items, setItems] = useState<Item[]>([]);

  useEffect(() => {
    const loading = async () => {
      const data = await getItems();

      setItems(data);
    };

    loading();
  }, [selected]);

  const getItems = async () => {
    try {
      const ids = selected.map((i) => i.itemId);
      const response = await fetch(`${GATEWAY_URL}/items/ids`, {
        method: "POST",
        body: JSON.stringify({ ids }),
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await response.json();
      return data;
    } catch (error) {
      console.error(error);
      return [];
    }
  };

  const onClickArrange = () => {
    if (!localStorage.getItem("token")) {
      showError("Необходимо зарегистрироваться!");
    } else router.push("/arrange");
  };

  return (
    <section className="cart" id="cart" style={{ flex: 2 }}>
      <h1 className="heading">
        Кор<span>зина</span>
      </h1>
      <div className="itemsTable" style={{ width: "35%" }}>
        <div className="th">
          <h1>ТОВАР</h1>
          <h1>ЦЕНА</h1>
        </div>
        {items.map((item) => (
          <CardItem
            name={item.name}
            price={item.price}
            quantity={findQuantity(item.id) ?? 1}
            key={item.id}
          />
        ))}
        <div className="th">
          <h1>ВСЕГО</h1>
          <h1>
            {items.reduce(
              (accum, current) =>
                accum +
                Number.parseFloat(current.price) *
                  (findQuantity(current.id) ?? 1),
              0
            )}
            ₽
          </h1>
        </div>

        <input
          style={{
            width: "50%",
            margin: "0 auto",
          }}
          onClick={() => onClickArrange()}
          type="submit"
          value="Оформить"
          className="btn"
        />
      </div>
    </section>
  );
}
